import {
    DesktopOutlined,
    FileOutlined,
    PieChartOutlined,
    TeamOutlined,
    UserOutlined,
  } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Menu } from 'antd';
import React, { useState } from 'react';
import {useNavigate,useLocation} from 'react-router-dom'
type MenuItem = Required<MenuProps>['items'][number];
const items: MenuItem[] = [
    {
        label:"栏目 1",
        key:'page1',
        icon:<PieChartOutlined />,
    },
    {
        label:"栏目 2",
        key:'page2',
        icon:<DesktopOutlined />,
    },
    {
        label:"栏目 3",
        key:'page3',
        icon:<UserOutlined />,
        children:[
            {
                label:"栏目 301",
                key:'page3/page301',
            },
            {
                label:"栏目 302",
                key:'page3/page302',
            },
            {
                label:"栏目 303",
                key:'page3/page303',
            }
        ]
    },
    {
        label:"栏目 4",
        key:'page4',
        icon:<TeamOutlined />,
        children:[
            {
                label:"栏目 401",
                key:'page4/page401',
            },
            {
                label:"栏目 402",
                key:'page4/page402',
            },
            {
                label:"栏目 403",
                key:'page4/page403',
            }
        ]
    },
    {
        label:"栏目 5",
        key:'page5',
        icon:<FileOutlined />,
    },
  ];
  const menus: React.FC = () => {
    const currentRouter = useLocation()
    console.log('currentRouter',currentRouter.pathname)

    const navigateTo = useNavigate()
    // 点击事件路由跳转
    const menuClick = (e:{key:String})=>{
      navigateTo(e.key)
    }
    let firstOpenKey:string = '';
    function findKey(obj:{key:String}){
        return obj.key === currentRouter.pathname
    }
    for(var i = 0; i <items.length; i++ ){
        if(items[i]!['children'] && items[i]!['children'].find(findKey)){
            firstOpenKey = items[i]!.key as string
            console.log('firstOpenKey',firstOpenKey)
            break
        }
    }
    const [openKeys, setOpenKeys] = useState([firstOpenKey]);
    // 展开回收某项菜单的时候执行该函数
    const onOpenChange = (key:string[])=>{
        setOpenKeys([key[key.length -1]])
    }
    return(
        <Menu theme="dark" 
            defaultSelectedKeys={[currentRouter.pathname]} 
            mode="inline" 
            items={items}
            onClick ={menuClick}
            // 当前展开项的key数组
            openKeys={openKeys}
            // 展开回收触发事件
            onOpenChange ={onOpenChange}
        />
    )
  }
  export default menus;